import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../controllers/order_list_controller.dart';

class OrderListView extends GetView<OrderListController> {
  const OrderListView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      appBar: AppBar(
        title: const Text('订单列表'),
        centerTitle: true,
        backgroundColor: Colors.white,
        foregroundColor: const Color(0xFF333333),
        elevation: 0,
        scrolledUnderElevation: 0,
        surfaceTintColor: Colors.transparent,
        shadowColor: Colors.transparent,
      ),
      body: Obx(() {
        if (controller.isLoading && controller.orderList.isEmpty) {
          return const Center(
            child: CircularProgressIndicator(color: Color(0xFF047FF7)),
          );
        }

        if (controller.orderList.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.receipt_long_outlined,
                  size: 80.w,
                  color: const Color(0xFF999999),
                ),
                SizedBox(height: 20.h),
                Text(
                  '暂无订单数据',
                  style: TextStyle(
                    fontSize: 28.sp,
                    color: const Color(0xFF666666),
                  ),
                ),
                SizedBox(height: 40.h),
                ElevatedButton(
                  onPressed: controller.refreshOrders,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF047FF7),
                    padding: EdgeInsets.symmetric(
                      horizontal: 40.w,
                      vertical: 20.h,
                    ),
                  ),
                  child: Text(
                    '重新加载',
                    style: TextStyle(fontSize: 28.sp, color: Colors.white),
                  ),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: controller.refreshOrders,
          color: const Color(0xFF047FF7),
          child: ListView.builder(
            padding: EdgeInsets.symmetric(vertical: 12.h),
            itemCount:
                controller.orderList.length + (controller.hasMore ? 1 : 0),
            itemBuilder: (context, index) {
              if (index == controller.orderList.length) {
                // 加载更多指示器
                return Container(
                  padding: EdgeInsets.all(20.h),
                  child: Center(
                    child:
                        controller.isLoading
                            ? const CircularProgressIndicator(
                              color: Color(0xFF047FF7),
                            )
                            : TextButton(
                              onPressed: controller.loadMoreOrders,
                              child: Text(
                                '加载更多',
                                style: TextStyle(
                                  fontSize: 26.sp,
                                  color: const Color(0xFF047FF7),
                                ),
                              ),
                            ),
                  ),
                );
              }

              final order = controller.orderList[index];
              return Column(
                children: [
                  if (index == 0) SizedBox(height: 0.h),
                  OrderItemCard(order: order, controller: controller),
                  SizedBox(
                    height:
                        index == controller.orderList.length - 1 ? 28.h : 30.h,
                  ),
                ],
              );
            },
          ),
        );
      }),
    );
  }
}

/// 订单项卡片组件
class OrderItemCard extends StatelessWidget {
  final CloudStorageOrder order;
  final OrderListController controller;

  const OrderItemCard({
    super.key,
    required this.order,
    required this.controller,
  });

  @override
  Widget build(BuildContext context) {
    final statusText = controller.getStatusText(order.status);
    final statusColor = Color(controller.getStatusColor(order.status));
    final cloudTypeText = controller.getCloudStorageTypeText(
      order.cloudStorageType,
    );

    return Container(
      width: Get.width,
      decoration: const BoxDecoration(color: Colors.white),
      child: Column(
        children: [
          // 订单号和状态栏
          Container(
            padding: EdgeInsets.symmetric(horizontal: 28.w, vertical: 22.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    // 左侧蓝色装饰条
                    Container(
                      width: 8.w,
                      height: 21.h,
                      decoration: BoxDecoration(
                        color: const Color(0xFF127FFF),
                        borderRadius: BorderRadius.circular(100.r),
                      ),
                    ),
                    SizedBox(width: 10.w),
                    Text(
                      '订单：${order.id}',
                      style: TextStyle(
                        fontSize: 26.w,
                        color: const Color(0xFF333333),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                Text(
                  statusText,
                  style: TextStyle(
                    fontSize: 22.sp,
                    color: statusColor,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          // 分割线
          Container(
            width: Get.width,
            height: 1.h,
            color: const Color(0xFFD8D8D8),
          ),
          // 订单详情区域
          Padding(
            padding: EdgeInsets.all(28.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 左侧图标
                Container(
                  width: 126.w,
                  height: 126.h,
                  padding: EdgeInsets.all(18.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFE6F7FF),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Image.asset(
                    'assets/images/order_left.png',
                    fit: BoxFit.contain,
                  ),
                ),
                SizedBox(width: 24.w),
                // 右侧信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '云存储订购',
                        style: TextStyle(
                          fontSize: 32.sp,
                          fontWeight: FontWeight.normal,
                          color: const Color(0xFF333333),
                          height: 1.0,
                        ),
                      ),
                      SizedBox(height: 20.h),
                      _buildInfoRow(
                        '通道名称：',
                        order.channelName.isNotEmpty ? order.channelName : '未知',
                      ),
                      SizedBox(height: 14.h),
                      _buildInfoRow('云存天数：', '${order.cloudStorageDuration}天'),
                      SizedBox(height: 14.h),
                      _buildInfoRow('云存类型：', cloudTypeText),
                      SizedBox(height: 14.h),
                      _buildInfoRow(
                        '云存生效时间：',
                        _formatDateTime(order.enableStartAt),
                      ),
                      SizedBox(height: 14.h),
                      _buildInfoRow(
                        '到期时间：',
                        _formatDateTime(order.enableEndAt),
                      ),
                      SizedBox(height: 14.h),
                      _buildInfoRow('云存码流：', '${order.cloudStorageStream}M'),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 22.sp,
            color: const Color(0xFF999999),
            fontWeight: FontWeight.normal,
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: TextStyle(
              fontSize: 22.sp,
              color: const Color(0xFF999999),
              fontWeight: FontWeight.normal,
            ),
          ),
        ),
      ],
    );
  }

  /// 格式化日期时间
  String _formatDateTime(String? dateTimeStr) {
    if (dateTimeStr == null || dateTimeStr.isEmpty) {
      return '——';
    }

    try {
      final dateTime = DateTime.parse(dateTimeStr);
      return '${dateTime.year}/${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}';
    } catch (e) {
      return dateTimeStr;
    }
  }
}
